#include "Defs.h"
#include "File.h"
#include "Exception.h"


File_T::File_T(const char * szFilename, DWORD dwDesiredAccess, DWORD dwShareMode, DWORD dwCreationDisposition, bool moveToEnd)
{
	_hFile = CreateFile(
		szFilename,
		dwDesiredAccess,
		dwShareMode,
		NULL,
		dwCreationDisposition,
		FILE_ATTRIBUTE_NORMAL,
		NULL);

	if( INVALID_HANDLE_VALUE == _hFile )
	{
		throw Exception_T(GetLastError(), "Error %d CreateFile(%s) - %s - %d - %s", GetLastError(), szFilename, __FILE__, __LINE__, __FUNCSIG__);
	}

	if( moveToEnd )
	{
		if( SetFilePointer(_hFile, 0, NULL, FILE_END) == INVALID_SET_FILE_POINTER )
		{
			throw Exception_T(GetLastError(), "Error %d SetFilePointer(%s) - %s - %d - %s", GetLastError(), szFilename, __FILE__, __LINE__, __FUNCSIG__);
		}
	}
}

File_T::~File_T()
{
	if( INVALID_HANDLE_VALUE != _hFile )
	{
		CloseHandle(_hFile);
	}
}

void File_T::Read(unsigned char * pb, unsigned int len)
{
	DWORD dw;
	if( !ReadFile(_hFile, pb, len, &dw, NULL) )
	{
		throw Exception_T(GetLastError(), "Error %d ReadFile - %s - %d - %s", GetLastError(), __FILE__, __LINE__, __FUNCSIG__);
	}
}

void File_T::Write(const char * sz)
{
	Write((unsigned char *)sz, lstrlen(sz));
}

void File_T::Write(unsigned char * pb, unsigned int len)
{
	DWORD dw;
	WriteFile(_hFile, pb, len, &dw, NULL);
}

bool File_T::Exists(const char * szFilename)
{
	try
	{
		File_T file(szFilename, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, false);
	}
	catch( Exception_T & )
	{
		return false;
	}
	
	return true;
}

unsigned int File_T::GetSize(const char * szFilename)
{
	File_T file(szFilename, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, false);
	unsigned int uiSize = GetFileSize(file._hFile, NULL);

	if( INVALID_FILE_SIZE == uiSize )
	{
		throw Exception_T(GetLastError(), "Error %d GetFileSize(%s) - %s - %d - %s", GetLastError(), szFilename, __FILE__, __LINE__, __FUNCSIG__);
	}

	return uiSize;
}